import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/login/entity/sv_entity.dart';
import 'package:shopping_group/modle/main/entity/commo_spec4app_record_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/route_util.dart';

class XianJianJuanPlayBloc implements BlocBase {
  //定时器
  Timer _timer;
  //设定时间
  int seconds = 0;
  //时间格式
  String _content = '00:59:59';

  // Stream来处理计数器
  StreamController<String> _counterController = StreamController<String>();
  StreamSink<String> get _inAdd => _counterController.sink;
  Stream<String> get sendDate => _counterController.stream;

  //  Stream来处理计数器上的操作
  StreamController<String> _actionController = StreamController<String>();
  //接收传值的对象
  StreamSink get incrementDate => _actionController.sink;

  StreamController<String> _timeController = StreamController<String>();
  //接收传值的对象
  StreamSink get timerDate => _timeController.sink;

  StreamController<Object> _initController = StreamController<Object>();
  StreamSink get initDate => _initController.sink;

  StreamController<Object> _addController = StreamController<Object>();
  StreamSink get _addDate => _addController.sink;
  Stream<Object> get sendData => _addController.stream;

  StreamController<Object> _validateController = StreamController<Object>();
  StreamSink get validateDate => _validateController.sink;

  StreamController<Object> _addPriceController = StreamController<Object>();
  StreamSink get _addPriceDate => _addPriceController.sink;
  Stream<Object> get sendPriceData => _addPriceController.stream;

  StreamController<Object> _playCompetController = StreamController<Object>();
  StreamSink get playCompetDate => _playCompetController.sink;
  XianJianJuanPlayBloc() {
    _timeController.stream.listen(timeData);
    _validateController.stream.listen(validateData);
    _initController.stream.listen(initData);
    _playCompetController.stream.listen(playCompeteData);
  }
  void timeData(data) {
    if (data is String) {
      _countDown(_content);
    }
  }

  _countDown(count) {
    _content = count;
    seconds = 3600; //1小时
    startTimer();
  }

  void startTimer() {
    //设置 1 秒回调一次
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      //更新界面
      //秒数减一，因为一秒回调一次
      seconds--;
      _content = constructTime(seconds);
      _inAdd.add(_content);
      if (seconds == 0) {
        //倒计时秒数为0，取消定时器
        cancelTimer();
      }
    });
  }

  //时间格式化，根据总秒数转换为对应的 hh:mm:ss 格式
  String constructTime(int seconds) {
    int hour = seconds ~/ 3600;
    int minute = seconds % 3600 ~/ 60;
    int second = seconds % 60;
    return formatTime(hour) +
        ":" +
        formatTime(minute) +
        ":" +
        formatTime(second);
  }

  //数字格式化，将 0~9 的时间转换为 00~09
  String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  void playCompeteData(data) {
    if (data is Map) {
      _playCompeteTask(data);
    }
  }

  void validateData(data) {
    if (data is Map) {
      _validateTask(data);
    }
  }

  void initData(data) {
    if (data is Map) {
      _initTask(data);
    }
  }

  void _playCompeteTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());

    //BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.XJJ_PLAY_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          eventBus.fire(
              'N' == data['byYonJin'] ? ZfbCompeteEvent() : YjCompeteEvent());
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _validateTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.XJJ_ISSHOP_URL, data: data, headers: {},
            success: (result) {
          //  BotToast.closeAllLoading();
          if (null != result) {
            SvEntity params = SvEntity.fromJson(result);
            if (BaseConstant.SUCESS == params.val) {
              eventBus.fire('N' == data['byYonJin']
                  ? ValidateXjjEvent(params.joinId)
                  : ValidateYjEvent(params.joinId));
            }
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _initTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.MONEY_JUAN_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            CommoSpec4AppRecordEntity params =
                CommoSpec4AppRecordEntity.fromJson(result);
            _addDate.add(params);
            _addPriceDate.add(params.realCharge);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _actionController?.close();
    _counterController?.close();
    _timeController?.close();
    _validateController?.close();
    _initController?.close();
    _addController?.close();
    _addPriceController?.close();
    _playCompetController?.close();
    cancelTimer();
  }
}
